<template>
  <view class="device-statistics-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="设备统计" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="search-filter-container">
            <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="false" placeholder="请输入停车场名称" @search="handleSearch"></up-search>
            
            <view class="filter-container">
              <up-dropdown>
                <up-dropdown-item v-model="searchForm.status" title="状态筛选" :options="statusOptions" @change="handleStatusChange" />
                <up-dropdown-item v-model="searchForm.deviceType" title="设备类型" :options="deviceTypeOptions" @change="handleDeviceTypeChange" />
              </up-dropdown>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 统计列表 -->
      <view class="statistics-list">
        <view class="statistics-item" v-for="(item, index) in currentList" :key="index">
          <view class="item-header">
            <view class="device-type">
              <up-tag :text="item.deviceTypeName" type="primary"></up-tag>
            </view>
            <view class="total-count">总计：{{ item.totalCount }}台</view>
          </view>
          <view class="item-content">
            <view class="status-item online">
              <view class="status-label">在线</view>
              <view class="status-count">{{ item.onlineCount }}台</view>
            </view>
            <view class="status-item offline">
              <view class="status-label">离线</view>
              <view class="status-count">{{ item.offlineCount }}台</view>
            </view>
          </view>
          <view class="item-footer">
            <up-button
              type="primary"
              size="small"
              @click="handleViewDistribution(item)">
              查看设备分布
            </up-button>
          </view>
        </view>
      </view>
    </z-paging>
    
    <!-- 设备分布弹窗 -->
    <up-popup v-model:show="showDistributionPopup" mode="bottom" :round="12" :mask-close="true" touchable="true" minHeight="80%">
      <view class="distribution-popup">
        <view class="popup-header">
          <text class="popup-title">设备分布情况</text>
          <up-icon name="close" size="24" @click="showDistributionPopup = false"></up-icon>
        </view>
        <view class="popup-content">
          <view class="device-info">
            <up-tag :text="currentDevice?.deviceTypeName" type="primary" v-if="currentDevice"></up-tag>
            <text class="device-count" v-if="currentDevice">总计：{{ currentDevice.totalCount }}台</text>
          </view>
          <view class="map-container">
            <map 
              :latitude="mapCenter.latitude" 
              :longitude="mapCenter.longitude"
              :markers="deviceMarkers"
              :scale="14"
              @markertap="handleMarkerTap"
            ></map>
          </view>
          <view class="device-list">
            <view 
              class="device-item" 
              v-for="(item, index) in mockDeviceList" 
              :key="index"
              :class="{selected: selectedDevice && selectedDevice.id === item.id}"
              @click="handleDeviceItemClick(item)"
            >
              <view class="device-info-row">
                <text class="device-name">{{ item.name }}</text>
                <text class="device-status" :class="item.status === '1' ? 'online' : 'offline'">{{ item.status === '1' ? '在线' : '离线' }}</text>
              </view>
              <view class="device-location" v-if="selectedDevice && selectedDevice.id === item.id">
                <text>位置: {{ item.location }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getRealNameVerifyList } from '@/api';

// z-paging 引用
const paging = ref(null);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  deviceType: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '在线', value: '1' },
  { label: '离线', value: '0' }
];

// 设备类型选项
const deviceTypeOptions = [
  { label: '全部', value: '' },
  { label: '道闸车牌识别', value: '1' },
  { label: '智能物联地磁', value: '2' },
  { label: '免布线视频桩', value: '3' },
  { label: '智能高位视频桩', value: '4' },
  { label: '物联网阻车器', value: '5' },
  { label: '智能巡检设备', value: '6' },
  { label: '智能物联闸机', value: '7' }
];

// 当前显示的列表数据
const currentList = ref([]);

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

// 处理搜索
const handleSearch = () => {
  fetchStatistics();
};

// 处理状态变化
const handleStatusChange = () => {
  fetchStatistics();
};

// 处理设备类型变化
const handleDeviceTypeChange = () => {
  fetchStatistics();
};

// 弹窗相关状态
const showDistributionPopup = ref(false);
const currentDevice = ref(null);
const mockDeviceList = ref([]);

// 地图相关状态
const mapCenter = ref({
  latitude: 23.021624,
  longitude: 113.121813
});
const deviceMarkers = ref([]);
const selectedDevice = ref(null);

// 处理查看设备分布
const handleViewDistribution = (item) => {
  currentDevice.value = item;
  // 生成模拟设备列表数据
  const deviceList = generateMockDeviceList(item);
  mockDeviceList.value = deviceList;
  
  // 生成地图标记点
  deviceMarkers.value = deviceList.map((device, index) => {
    // 随机生成设备在地图上的位置（围绕中心点）
    const latitude = mapCenter.value.latitude + (Math.random() - 0.5) * 0.02;
    const longitude = mapCenter.value.longitude + (Math.random() - 0.5) * 0.02;
    
    return {
      id: device.id,
      latitude,
      longitude,
      width: 30,
      height: 30,
      iconPath: device.status === '1' ? '/static/images/marker_online.svg' : '/static/images/marker_offline.svg',
      callout: {
        content: device.name,
        color: '#000000',
        fontSize: 12,
        borderRadius: 4,
        padding: 5,
        display: 'BYCLICK'
      }
    };
  });
  
  showDistributionPopup.value = true;
};

// 处理标记点点击
const handleMarkerTap = (e) => {
  const markerId = e.markerId;
  const device = mockDeviceList.value.find(item => item.id === markerId);
  if (device) {
    selectedDevice.value = device;
    updateSelectedMarker(device);
  }
};

// 处理设备列表项点击
const handleDeviceItemClick = (device) => {
  selectedDevice.value = device;
  updateSelectedMarker(device);
  
  // 将地图中心移动到选中的设备位置
  const marker = deviceMarkers.value.find(m => m.id === device.id);
  if (marker) {
    mapCenter.value = {
      latitude: marker.latitude,
      longitude: marker.longitude
    };
  }
};

// 更新选中的标记点
const updateSelectedMarker = (device) => {
  // 更新标记点，显示被选中设备的详细信息
  deviceMarkers.value = deviceMarkers.value.map(marker => {
    if (marker.id === device.id) {
      return {
        ...marker,
        callout: {
          ...marker.callout,
          content: `${device.name}\n状态: ${device.status === '1' ? '在线' : '离线'}\n位置: ${device.location}`,
          display: 'ALWAYS'
        }
      };
    } else {
      // 重置其他标记点的callout显示
      return {
        ...marker,
        callout: {
          ...marker.callout,
          display: 'BYCLICK'
        }
      };
    }
  });
};

// 生成模拟设备列表
const generateMockDeviceList = (deviceItem) => {
  const result = [];
  const total = deviceItem.totalCount;
  const online = deviceItem.onlineCount;
  
  // 生成在线设备
  for (let i = 0; i < online; i++) {
    result.push({
      id: `${deviceItem.deviceTypeId}-online-${i}`,
      name: `${deviceItem.deviceTypeName}-${i+1}`,
      status: '1',
      location: '停车场' + (i % 5 + 1)
    });
  }
  
  // 生成离线设备
  for (let i = 0; i < (total - online); i++) {
    result.push({
      id: `${deviceItem.deviceTypeId}-offline-${i}`,
      name: `${deviceItem.deviceTypeName}-${online+i+1}`,
      status: '0',
      location: '停车场' + (i % 5 + 1)
    });
  }
  
  return result;
};

// 生成模拟统计数据
const generateMockStatistics = () => {
  return deviceTypeOptions.filter(item => item.value !== '').map((deviceType, index) => {
    const onlineCount = Math.floor(Math.random() * 50) + 10;
    const offlineCount = Math.floor(Math.random() * 20) + 5;
    return {
      id: deviceType.value,
      deviceTypeId: deviceType.value,
      deviceTypeName: deviceType.label,
      onlineCount,
      offlineCount,
      totalCount: onlineCount + offlineCount
    };
  });
};

// z-paging查询方法
const queryList = async (pageNo, pageSize) => {
  try {
    // 这里应该调用实际的API获取统计数据
    // const result = await getDeviceStatistics({ ...searchForm, pageNo, pageSize });
    
    // 模拟数据
    const mockData = generateMockStatistics();
    
    // 模拟分页
    const startIndex = (pageNo - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = mockData.slice(startIndex, endIndex);
    
    const result = {
      list: pageData,
      total: mockData.length
    };
    
    paging.value.complete(result.list);
  } catch (error) {
    console.error('获取统计数据失败', error);
    paging.value.complete(false);
    uni.showToast({
      title: '获取数据失败',
      icon: 'error'
    });
  }
};

// 获取统计数据
const fetchStatistics = () => {
  paging.value?.reload();
};

onMounted(() => {
  fetchStatistics();
});
</script>

<style lang="scss" scoped>
.device-statistics-page {
  .search-filter-container {
    .filter-container {
      margin-top: 20rpx;
    }
  }

  .statistics-list {
    padding: 0 20rpx;

    .statistics-item {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        .device-type {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }

        .total-count {
          font-size: 28rpx;
          color: #666;
        }
      }

      .item-content {
        display: flex;
        justify-content: space-around;
        margin-bottom: 30rpx;

        .status-item {
          text-align: center;

          .status-label {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 10rpx;
          }

          .status-count {
            font-size: 36rpx;
            font-weight: bold;
          }

          &.online .status-count {
            color: #19be6b;
          }

          &.offline .status-count {
            color: #fa3534;
          }
        }
      }

      .item-footer {
        text-align: center;
      }
    }
  }
  
  // 设备分布弹窗样式
  .distribution-popup {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: auto;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1px solid #eee;
      
      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .popup-content {
      flex: 1;
      padding: 20rpx;
      overflow-y: auto;
      
      .device-info {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        
        .device-count {
          margin-left: 20rpx;
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .map-container {
        height: 400rpx;
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        overflow: hidden;
        
        map {
          width: 100%;
          height: 100%;
        }
      }
      
      .device-list {
        .device-item {
          padding: 20rpx;
          border-bottom: 1px solid #eee;
          transition: all 0.3s;
          
          &.selected {
            background-color: #f0f9ff;
            border-left: 4rpx solid #1890ff;
          }
          
          .device-info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
          
          .device-name {
            font-size: 28rpx;
            color: #333;
          }
          
          .device-status {
            font-size: 28rpx;
            font-weight: bold;
            
            &.online {
              color: #19be6b;
            }
            
            &.offline {
              color: #fa3534;
            }
          }
          
          .device-location {
            margin-top: 10rpx;
            font-size: 24rpx;
            color: #666;
          }
        }
      }
    }
  }
}
</style>